﻿using ETA.Common;
using ETA.Dtos;
using ETA.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ETA.Entity;
using AttributeRouting;
using AttributeRouting.Web.Http;
using ETA.WebAPI.Models;
using ETA.DomainEnum;


namespace ETA.WebAPI.Controllers
{
    /// <summary>
    /// 所有请求请加上在请求头中加上 AuthToken:4b12c526-16cd-451f-ba85-3b4d0729eaf0
    /// </summary>
    public class UserController : BaseController
    {
        private static IUserService _IUserService { set; get; }
        private static IReferrerLogService _IReferrerLogService { set; get; }
        private static IWebMessageService _IWebMessageService { set; get; }

        public UserController(IWebMessageService IWebMessageService, IUserService service, IReferrerLogService IReferrerLogService)
        {
            _IUserService = service;
            _IReferrerLogService = IReferrerLogService;
            _IWebMessageService = IWebMessageService;
        }

        /// <summary>
        /// 验证码发送
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="identifyCode"></param>
        /// <returns></returns>
        [GET("SendCheckNum")]
        public ApiResDTO GetSendCheckNum(string phone, string identifyCode)
        {
            var res = new ApiResDTO();
            var isExist = _IUserService.CheckMobile(phone);
            if (isExist)
            {
                res.ResultDesc = "该号码已经被其他用户使用";
                return res;
            }
            var checkNum = _IUserService.SendCheckNum(phone, identifyCode);
            if (!string.IsNullOrEmpty(checkNum))
            {
                res.Result = ResultEnum.Success;
                res.ResultDesc = checkNum;
            }
            else
            {
                res.ResultDesc = "发送失败";
            }
            return res;
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="dto">通用请求类</param>
        /// <returns></returns>
        [GET("LoginCheck")]
        public HttpResponseMessage GetLoginCheck([FromUri]LoginCheckReqDTO dto)
        {
            var res = new LoginCheckResDTO();
            if (ModelState.IsValid)
            {
                var req1 = new QueryUserRequest
                {
                    User = new User
                    {
                        Email = dto.Account
                    }
                };
                var req2 = new QueryUserRequest
                {
                    User = new User
                    {
                        Mobile = dto.Account
                    }
                };

                var req3 = new QueryUserRequest
                {
                    User = new User
                    {
                        LoginName = dto.Account
                    }
                };
                var response1 = _IUserService.QueryUser(req1);
                var response2 = _IUserService.QueryUser(req2);
                var response3 = _IUserService.QueryUser(req3);
                dto.Password = CommHelper.Base64Encrypt(dto.Password);
                if (response1.Result.IsSuccess && response1.Users.Any())
                {
                    if (response1.Users.FirstOrDefault().Password == dto.Password)
                    {
                        res.Result = ResultEnum.Success;
                        res.ResultDesc = response1.DtoUsers.FirstOrDefault();
                    }
                }
                else
                    if (response2.Result.IsSuccess && response2.Users.Any())
                    {
                        if (response2.Users.FirstOrDefault().Password == dto.Password)
                        {
                            res.Result = ResultEnum.Success;
                            res.ResultDesc = response2.DtoUsers.FirstOrDefault();
                        }
                    }
                    else
                        if (response3.Result.IsSuccess && response3.Users.Any())
                        {
                            if (response3.Users.FirstOrDefault().Password == dto.Password)
                            {
                                res.Result = ResultEnum.Success;
                                res.ResultDesc = response3.DtoUsers.FirstOrDefault();
                            }
                        }
                if (res.Result == ResultEnum.Fail)
                {
                    res.ResultDesc = "您输入的用户名或者密码错误";
                }

            }
            var queryRes = Request.CreateResponse(HttpStatusCode.OK, res);
            return queryRes;
        }

        /// <summary>
        /// 个人用户注册
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [GET("AddUser")]
        public ApiResDTO GetAddUser([FromUri]AddUserReqDTO dto)
        {
            var createUserResponse = new ApiResDTO();
            var err = string.Empty;
            var userDto = new UserDto
            {
                Email = dto.Email,
                LoginName = dto.Phone,
                Mobile = dto.Phone,
                Password = dto.Password,
                UserName = dto.Name
            };

            if (_IUserService.CheckMobile(userDto.Mobile))
            {
                err += "该号码已经被其他用户使用#";
            }

            if (_IUserService.CheckEmail(userDto.Email))
            {
                err += "该邮箱已经被其他用户使用#";
            }

            if (!string.IsNullOrEmpty(err))
            {
                createUserResponse.ResultDesc = err;
                return createUserResponse;
            }

            if (ModelState.IsValid)
            {
                var queryRolerResponse = _IUserService.QueryRoler(new QueryRolerRequest());
                if (queryRolerResponse.Result.IsSuccess)
                {
                    var shiXiSheng = queryRolerResponse.Rolers.First(q => q.RolerName == "实习生");
                    userDto.UserId = Guid.NewGuid().ToString();
                    userDto.Rolers = new List<Roler>() { shiXiSheng };
                    //userDto.Password = CommHelper.Base64Encrypt(userDto.Password);
                    var createUserReq = new CreateUserRequest
                    {
                        UserDto = userDto
                    };
                    var resp = _IUserService.AddUser(createUserReq);
                    if (resp.Result.IsSuccess)
                    {
                        createUserResponse.Result = ResultEnum.Success;
                        createUserResponse.ResultDesc = resp.UserDto;
                    }
                }
            }
            return createUserResponse;
        }

        /// <summary>
        /// 根据手机号码返回用户信息  GET api/user/18221647820
        /// </summary>
        /// <param name="id">手机号码,邮箱</param>
        /// <returns></returns>
        public HttpResponseMessage Get(string id)
        {
            HttpResponseMessage msg = null;
            var req = new QueryUserRequest
            {
                User = new User
                {
                    Mobile = id
                }
            };
            var response = _IUserService.QueryUser(req);
            if (response.Result.IsSuccess)
            {
                msg = Request.CreateResponse(HttpStatusCode.OK, response.Users);
            }
            else
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "查询失败");
            }
            return msg;
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="strNum">手机号码或者邮箱</param>
        /// <param name="type">0 手机 1 邮箱</param>
        /// <returns></returns>
        [GET("GetPassword")]
        public ApiResDTO GetPassword(string strNum, int type)
        {
            var res = new ApiResDTO();
            var response = _IUserService.GetPassword(strNum, (GetpwdType)type);
            if (response.Result.IsSuccess)
            {
                res.Result = ResultEnum.Success;
            }
            else
            {
                res.ResultDesc = response.Result.ErrMessage;
            }
            return res;
        }

        /// <summary>
        /// 获取积分数据
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [GET("ReferrerLog")]
        public ApiResDTO GetReferrerLogList(string userId)
        {
            var res = new ApiResDTO();
            try
            {
                var list = new List<ReferrerLog>();
                var count = 0;
                var response = _IReferrerLogService.QueryReferrerLogList(
                new QueryReferrerLogRequest
                {
                    UserId = userId,
                    Page = 1,
                    PageSize = int.MaxValue
                }, out count
                );
                if (response.Result.IsSuccess)
                {
                    list = response.ReferrerLogs.ToList();
                }
                int? pointTotal = 0; //总积分
                int? unUsedPointTotal = 0;//总可用积分

                var dtoList = new List<ReferrerLogDto>();
                foreach (var l in list)
                {
                    var point = l.Point;
                    var usedPoint = l.UsedPoint;
                    var referrer = l.Referrer;//推荐者
                    var referrerName = referrer.UserName;
                    var referrerId = referrer.UserId;
                    var registerDate = referrer.CreateDate.ToShortDateString();
                    var rb = referrer.RegistrationBind;//出国绑定信息
                    int? unUsedPoint = 0;//可用积分
                    var abroadDate = string.Empty;
                    if (rb != null)
                    {
                        abroadDate = rb.CreateDate.ToShortDateString();//出国时间
                        unUsedPoint = point - (usedPoint.HasValue ? usedPoint : 0);
                    }

                    pointTotal += point;
                    unUsedPointTotal += unUsedPoint;
                    dtoList.Add(new ReferrerLogDto
                    {
                        AbroadDate = abroadDate,
                        Point = point.HasValue ? point.ToString() : "",
                        RegisterDate = registerDate,
                        UnUsedPoint = unUsedPoint.HasValue ? unUsedPoint.ToString() : "",
                        UserId = referrerId,
                        UserName = referrerName
                    });
                }
                var returnObj = new { PointTotal = pointTotal, UsedPointTotal = unUsedPointTotal, DataList = dtoList };
                res.ResultDesc = returnObj;
                res.Result = ResultEnum.Success;
            }
            catch (Exception e)
            {
                res.Result = ResultEnum.Fail;
            }
            return res;
        }

        [GET("GetMessage")]
        public ApiResDTO GetMessage(string userId)
        {
            var res = new ApiResDTO();
            var messageList = new List<WebMessage>();
            var queryRes = _IWebMessageService.QueryWebMessageList(new QueryWebMessageRequest
            {
                WebMessage = new Entity.WebMessage
                {
                    UserId = userId
                }
            });
            if (queryRes.Result.IsSuccess)
            {
                var messageDtos = new List<MessageDto>();
                messageList = queryRes.WebMessageList.ToList();
                foreach (var m in messageList)
                {
                    messageDtos.Add(new MessageDto
                    {
                        Content = m.Content,
                        CreateTime = m.CreateDate.ToString("yyyy-MM-dd HH:mm"),
                        MailFrom = "出国直通车",
                        State =(int)m.MessageOpenEnum,
                        WebMessageId = m.WebMessageId
                    });
                }
                res.ResultDesc = messageDtos;
                res.Result = ResultEnum.Success;
            }
            return res;
        }

        [GET("ReadMessage")]
        public ApiResDTO GetReadMessage(string msgId)
        {
            var res = new ApiResDTO();
            var queryRes = _IWebMessageService.QueryWebMessageList(new QueryWebMessageRequest
            {
                WebMessage = new Entity.WebMessage
                {
                    WebMessageId = msgId
                }
            });
            if (queryRes.Result.IsSuccess)
            {
                var msg = queryRes.WebMessageList.First();
                if (msg != null)
                {
                    msg.MessageOpenEnum = DomainEnum.MessageOpenEnum.已读;
                    msg.ModifyDate = DateTime.Now;
                    var modifyres = _IWebMessageService.ModifyWebMessageService(new ModifyWebMessageRequest
                    {
                        WebMessage = msg
                    });
                    if (modifyres.Result.IsSuccess)
                    {
                        res.Result = ResultEnum.Success;
                    }
                    else
                    {
                        res.ResultDesc = modifyres.Result.ErrMessage;
                        res.Result = ResultEnum.Fail;
                    }
                }
            }
            return res;
        }

        [GET("GetNotReadMessageNum")]
        public ApiResDTO GetNotReadMessage(string userId)
        {
            var res = new ApiResDTO();
            var count = 0;
            var queryRes = _IWebMessageService.QueryWebMessageList(new QueryWebMessageRequest
            {
                WebMessage = new Entity.WebMessage
                {
                    UserId = userId
                }
            });
            if (queryRes.Result.IsSuccess)
            {
                count = queryRes.WebMessageList.Count(w => w.MessageOpenEnum == DomainEnum.MessageOpenEnum.未读);
                res.Result = ResultEnum.Success;
                res.ResultDesc = new { Count = count };
            }
            else
            {
                res.Result = ResultEnum.Fail;
                res.ResultDesc = queryRes.Result.ErrMessage;
            }
            return res;
        }



    }
}
